<template>
  <el-dialog
    :title="dialogType === 'add' ? '添加角色' : '修改角色信息'"
    v-model="dialogVisible"
    width="700px"
    :close-on-click-modal="false"
    @closed="handleDialogClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="180px"
      label-position="right"
    >
      <el-form-item label="角色名称:" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入"
          :maxlength="100"
          :show-word-limit="true"
        />
      </el-form-item>

      <el-form-item label="组织类型:" prop="orgType">
        <el-select
          v-model="form.orgType"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option label="Zendure" value="Zendure" />
          <el-option label="Installer" value="Installer" />
          <el-option label="Distributor" value="Distributor" />
          <el-option
            label="Organizational Customer"
            value="Organizational Customer"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="权限类型:" prop="authorityType">
        <el-select
          v-model="form.authorityType"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option label="App" value="App" />
          <el-option label="Web" value="Web" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态:" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="true"
          :inactive-value="false"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <el-form-item label="备注:" prop="note">
        <el-input
          v-model="form.note"
          type="textarea"
          :rows="4"
          placeholder="请输入备注"
          :maxlength="200"
          :show-word-limit="true"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="flex justify-end gap-2">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// 角色编辑对话框（简版）
// 职责：
// - 新增/修改角色的基础信息
// - 校验并回传表单数据给父组件
import type { FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch } from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  dialogType: {
    type: String,
    default: "add" // 'add' 或 'edit'
  }
});

const emit = defineEmits(["update:visible", "submit-success"]);

// 表单实例与显隐
const formRef = ref<FormInstance>();
const dialogVisible = ref(props.visible);

// 表单数据
const form = reactive({
  name: "",
  orgType: "",
  authorityType: "",
  status: true,
  note: "",
  updateUser: "system@example.com"
});

// 验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    {
      max: 100,
      message: "角色名称不能超过100个字符",
      trigger: "blur"
    }
  ],
  orgType: [{ required: true, message: "请选择组织类型", trigger: "change" }],
  authorityType: [{ required: true, message: "请选择权限类型", trigger: "change" }],
  note: [
    {
      max: 200,
      message: "备注不能超过200个字符",
      trigger: "blur"
    }
  ]
});

// 监听可见性：父传入 visible 改变时同步对话框显隐
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
  }
);

// 监听对话框可见性：同步回父组件
watch(
  () => dialogVisible.value,
  val => {
    emit("update:visible", val);
  }
);

// 监听传入的表单数据：编辑态回填
watch(
  () => props.formData,
  val => {
    if (Object.keys(val).length > 0) {
      Object.assign(form, val);
    }
  },
  { immediate: true, deep: true }
);

// 提交表单：校验通过后回传给父组件
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // 表单验证通过，提交数据
      emit("submit-success", {
        ...form,
        // 区分新增和编辑操作
        isAdd: props.dialogType === "add"
      });
    }
  });
};

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  Object.assign(form, {
    name: "",
    orgType: "",
    authorityType: "",
    status: true,
    note: "",
    updateUser: "system@example.com"
  });
};
</script>
